using System;
using System.Text;
using System.Web.UI;
using Mindscape.BackgroundMotion.Website.Infrastructure;

namespace Mindscape.BackgroundMotion.Website.Controls
{
  /// <summary>
  /// This class is used to handle collections of items which need to be paged for display and have a list of pages displayed
  /// </summary>
  public partial class PagingControl : UserControl
  {
    private ISearchResult _searchResults;

    /// <summary>
    /// Gets or sets the search results.
    /// </summary>
    public ISearchResult SearchResults
    {
      get { return _searchResults; }
      set { _searchResults = value; }
    }

    /// <summary>
    /// Returns the anchor links for pages in the current set of search results
    /// </summary>
    /// <returns>A string containing an anchor link for each page of search results in the collection</returns>
    public string PagingLinks
    {
      get
      {
        StringBuilder sb = new StringBuilder();
        string filter = Request.Params[Constants.Parameters.Filter];
        string query = Request.Params[Constants.Parameters.Query];
        string userId = Request.Params[Constants.Parameters.UserID];

        for(int i=1; i<= _searchResults.Pages; i++)
        {
          string selected = string.Empty;

          if (i == _searchResults.PageNumber)
          {
            selected = "class=\"selected\"";
          }

          sb.AppendFormat("<a {0} href=\"{1}?{2}={3}&{4}={5}&{6}={7}&{8}={9}\">{7}</a>",
                          selected,
                          Request.Url.AbsolutePath,
                          Constants.Parameters.Filter,
                          filter,
                          Constants.Parameters.Query,
                          query,
                          Constants.Parameters.Page,
                          i,
                          Constants.Parameters.UserID,
                          userId);
        }

        return sb.ToString();
      }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      if (_searchResults == null || _searchResults.TotalResults == 0)
      {
        Visible = false;
      }
    }
  }
}